package com.lhl.jwt.security.handler;

import com.lhl.jwt.security.define.JwtConstant;
import com.lhl.jwt.util.CacheManager;
import com.nimbusds.jwt.SignedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * 注销登录 将token 加入黑名单
 * @author king
 */
@Slf4j
public class LogoutBlacklistHandler implements LogoutHandler {

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		try {
			SignedJWT jwt = getJwtToken(request);

			CacheManager.setData(jwt.getParsedString(), jwt, extractExpireTime(jwt));
		}catch (ParseException e){
			e.printStackTrace();
		}

	}

	private int extractExpireTime(SignedJWT jwt) throws ParseException {
		int expire = 0;
		Date expiresAt = jwt.getJWTClaimsSet().getExpirationTime();
		if (!expiresAt.before(Calendar.getInstance().getTime())) {
			expire = (int) (expiresAt.getTime() - System.currentTimeMillis());
		} 
		return expire;
	}
	
	private SignedJWT getJwtToken(HttpServletRequest request) throws ParseException {
		String authInfo = request.getHeader(JwtConstant.AUTHORIZATION_HEADER);
		if (StringUtils.isBlank(authInfo)) {
			throw new BadCredentialsException(JwtConstant.TOKEN_NOT_EMPTY);
		}
		return SignedJWT.parse(StringUtils.removeStart(authInfo, JwtConstant.AUTHORIZATION_START_STRING));
	}

}
